const Cp = require("../../utils/common-page")
const co = require("../../vendor/co")
const regeneratorRuntime = require("../../vendor/regenerator-runtime")
class Search extends Cp {
    constructor() {
        super()

        this.addMethod("choosePosition", e => {
            console.log(e)
            wx.chooseLocation({
                success: res => {
                    this.address = res.name
                    this.location = { latitude: res.latitude, longitude: res.longitude }
                    this.emit("choose", res)
                },
            })
        })
    }

    getAddress() {
        co(function* () {
            //获取经纬度
            if (!this.location) {
                const location = yield getApp().toPromise(wx.getLocation, { type: "gcj02" })
                this.location = location
            }
            //获取高德信息
            if (!this.gdInfo) {
                const gd = yield getApp().http.get("city/store/gaode")
                this.gdInfo = gd.data
            }
            //获取当前位置
            if (!this.address) {
                let formatAdd = "定位失败，请重试"
                if (this.location) {
                    const position = yield getApp().toPromise(wx.request, {
                        url: "https://restapi.amap.com/v3/geocode/regeo",
                        data: {
                            key: this.gdInfo.key,
                            location: [this.location.longitude, this.location.latitude].join(","),
                            poitype: '商务写字楼|小区|街道',
                            extensions: 'base'
                        }
                    })
                    try {
                        formatAdd = position.data.regeocode.formatted_address
                        formatAdd = formatAdd.replace(position.data.regeocode.addressComponent.province, "")
                        formatAdd = formatAdd.replace(position.data.regeocode.addressComponent.city, "")
                        formatAdd = formatAdd.replace(position.data.regeocode.addressComponent.district, "")
                        formatAdd = formatAdd.replace(position.data.regeocode.addressComponent.township, "")
                    } catch (err) {

                    }
                }
                this.address = formatAdd
            }
            this.emit("getAddressSuccess", { address: this.address, location: this.location })
        }.bind(this))
        return this
    }
}

module.exports = Search